package com.enzoism.springboot.juc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.*;

public class MyThreadPoolExecutor5 {

    private static Logger logger = LoggerFactory.getLogger(MyThreadPoolExecutor5.class.getName());

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService threadPoolExecutor = Executors.newCachedThreadPool();
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(threadPoolExecutor);
        /**
         * execute、submit、schedule区别
         * 1）execute：   执行线程（添加到任务workers中）
         * 2）submit：    异步线程（返回的就是Future）
         * 3）schedule：  调度线程（调度线程专有）
         */
        int num = 20;
        for (int i = 0; i < num; i++) {
            completionService.submit(new MyCallable());
        }
        logger.info("----------->异步线程执行成功");
        for (int i = 0; i < num; i++) {
            Integer integer = completionService.take().get();
            logger.info("--->异步线程的执行结果：" + integer);
        }

        threadPoolExecutor.shutdown();
        threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("----->线程结束退出");
    }

    private static class MyCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int result = Math.abs((new Random().nextInt(500) % 1000)) + 2000;
            System.out.println("------"+Thread.currentThread().getName()+" 时间："+result);
            Thread.sleep(result);
            return result;
        }
    }
}
